package cn.elead.it.sso.core.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.elead.it.sso.core.constant.GlobalVariable;
import cn.elead.it.sso.core.path.AntPathMatcher;
import cn.hutool.json.JSONUtil;

/**
 * 客户端过滤器
 * 
 * @author luopeng
 *
 */
@SuppressWarnings("serial")
public abstract class SsoFilter extends HttpServlet implements Filter {

	private static Logger logger = LoggerFactory.getLogger(SsoFilter.class);

	protected static final AntPathMatcher antPathMatcher = new AntPathMatcher();

	protected List<String> excludedPaths = new ArrayList<String>();
	{
		excludedPaths.add("/static/images/**");
		excludedPaths.add("/static/videos/**");
		excludedPaths.add("/*.html");
		excludedPaths.add("/**/*.html");
		excludedPaths.add("/**/*.css");
		excludedPaths.add("/**/*.js");
		excludedPaths.add("/*/api-docs");
		excludedPaths.add("/swagger-ui.html");
		excludedPaths.add("/swagger-resources/**");
		excludedPaths.add("/swagger-resources/**");
		excludedPaths.add("/swagger-resources/**");
		excludedPaths.add("/swagger-resources/**");
		excludedPaths.add("/webjars/**");
	}
	
	/**
	 * 添加过滤路径
	 * @param filterConfig
	 */
	protected void addExcludedPath(FilterConfig filterConfig) {
		String paths = filterConfig.getInitParameter(GlobalVariable.SSO_EXCLUDED_PATHS);
		if(paths != null && paths.trim().length() > 0) {
			for (String path : paths.split(",")) {
				excludedPaths.add(path);
			}
		}
	}

	/**
	 * 向外输出json对象
	 *
	 * @param obj
	 */
	protected void writeValueAsJson(HttpServletResponse response, HttpServletRequest req, Object obj) {
		if (response.isCommitted()) {
			logger.warn("Warn: Response isCommitted, Skip the implementation of the method.");
			return;
		}
		response.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD");
		response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-token, sso_sessionid ,Authorization");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setContentType("application/json;charset=utf-8");
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		try (PrintWriter writer = response.getWriter()) {
			writer.print(JSONUtil.toJsonStr(obj));
			writer.flush();
		} catch (IOException e) {
			logger.warn("Error: Response printJson faild, stackTrace: {}", e);
		}
	}

}
